"""
searches.py

Created by Mike Thorpe on 2009-07-25.
Copyright (c) 2009 Mike Thorpe. All rights reserved.
"""
import logging
import cgi

from google.appengine.api import urlfetch
from google.appengine.ext import db

from xml.dom import minidom
from django.utils import simplejson as json

class SavedSearch(db.Model):
  """
  A set of search terms
  
  get_included_terms,
  get_excluded_terms:
    Returns a GQL Query object 
    
  """
  name = db.StringProperty()
  user = db.UserProperty()
  email = db.EmailProperty()
  
  def get_included_terms(self):
    q = SearchTerm.all()
    q.filter("saved_search =", self)
    q.filter("is_excluded =", False)
    return q
  
  def get_excluded_terms(self):
    q = SearchTerm.all()
    q.filter("saved_search =", self)
    q.filter("is_excluded =", True)
    return q
    
  def get_common_searches(self):
    q = CommonSearch.all()
    q.filter("saved_search =", self)
    return q

  def add_search_term(self, search_string, excluded=False):
    SearchTerm(saved_search=self, 
               search_string=cgi.escape(search_string), 
               is_excluded=excluded
               ).put()

  def delete_search_term(self, search_term_key):
    term = SearchTerm.get(search_term_key)
    if term:
      term.delete()
    
  def add_common_search(self, search_string, enabled=True):
    CommonSearch(saved_search=self, 
              search_string=cgi.escape(search_string), 
              is_enabled=enabled
              ).put()
                
  def absolute_url(self):
    return "/saved_search/" + str(self.name)

class SearchTerm(db.Model):
  """
  Parent for search terms.
  Provides Methods for returning lists or terms
  and adding new ones.
  """ 
  saved_search = db.ReferenceProperty(SavedSearch,required=True)
  search_string = db.StringProperty(required=True)
  is_excluded = db.BooleanProperty(default=False)
    
  def remove_url(self):
    url = '/'.join([self.saved_search.absolute_url() , "delete/term", str(self.key())])
    return url
  

    
class CommonSearch(db.Model):
  """
  Common search strings, to display as a list to be selected from.
  """
  saved_search = db.ReferenceProperty(SavedSearch,required=True)
  search_string = db.StringProperty(required=True)
  is_enabled = db.BooleanProperty(default=False)
  
class Fixtures(db.Model):
  """
  For testing
  
  from google.appengine.api import users
  from searches_model import *

  user = users.get_current_user()
  Fixtures().create_defaults(user)
  
  """
  def create_defaults(self, user):
    ss = SavedSearch(user=user,name="default",email=user.email()).put()
    ss = SavedSearch.get(ss)
    ss.add_common_search("sale")
    ss.add_common_search("% off")
    ss.add_common_search("now available")
    
    ss.add_search_term("Trine")
    ss.add_search_term("Half Life 2")
    ss.add_search_term("Nancy Drew", True)
    